import random
import chardet
import urllib.parse
import urllib.request

def post(request):
    response = urllib.request.urlopen(request)
    page = response.read()

    return page.decode('utf8')

def getHash(source):
    viewstateop = source.find('id="__VIEWSTATE"', 0, -1) + 24
    viewstateed = source.find('"', viewstateop, -1)
    viewstate = source[viewstateop : viewstateed]

    eventvalidationop = source.find('id="__EVENTVALIDATION"', viewstateed, -1) + 30
    eventvalidationed = source.find('"', eventvalidationop, -1)
    eventvalidation = source[eventvalidationop : eventvalidationed]

    return viewstate, eventvalidation

def getBalance(source):
    balanceop = source.find(u'您的剩余电量：', 0, -1)
    balanceop = source.find('value="', balanceop, -1) + 7
    balanceed = source.find('"', balanceop, -1)
    balance = source[balanceop : balanceed]

    return float(balance)

def crawler(programId, txtyq, txtId, Txtroom):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.56 (KHTML, like Gecko) Version/9.0 Safari/601.1.56'
    }

    goalUrl = 'http://202.114.18.218/main.aspx'
    response = urllib.request.urlopen(goalUrl)
    source = response.read().decode('utf8')

    viewstate, eventvalidation = getHash(source)
    values = {
        '__EVENTTARGET'     :   '',
        '__EVENTARGUMENT'   :   '',
        '__VIEWSTATE'       :   viewstate,
        '__EVENTVALIDATION' :   eventvalidation,
        'programId'         :   programId,
        'Txtroom'           :   '',
        'TextBox2'          :   '',
        'TextBox3'          :   ''
    }
    data = urllib.parse.urlencode(values).encode('utf8')
    request = urllib.request.Request(url=goalUrl, data=data, headers=headers)

    source = post(request)
    viewstate, eventvalidation = getHash(source)
    values['__EVENTTARGET'] = 'txtyq'
    values['__VIEWSTATE'] = viewstate
    values['__EVENTVALIDATION'] = eventvalidation
    values['txtyq'] = txtyq
    data = urllib.parse.urlencode(values).encode('utf8')
    request = urllib.request.Request(url=goalUrl, data=data, headers=headers)

    source = post(request)
    viewstate, eventvalidation = getHash(source)
    values['__EVENTTARGET'] = ''
    values['__VIEWSTATE'] = viewstate
    values['__EVENTVALIDATION'] = eventvalidation
    values['txtId'] = txtId
    values['Txtroom'] = Txtroom
    values['ImageButton1.x'] = 0
    values['ImageButton1.y'] = 0
    data = urllib.parse.urlencode(values).encode('utf8')
    request = urllib.request.Request(url=goalUrl, data=data, headers=headers)

    source = post(request)
    return getBalance(source)

if __name__ == "__main__":
    print(crawler(programId=u'东区', txtyq=u'沁苑东十三舍', txtId=u'1层', Txtroom=u'101'))
